package com.comecrd.controller;

import com.comecrd.model.User;
import com.comecrd.model.dto.UserDTO;
import com.comecrd.service.UserService;
import com.comecrd.util.JWTUtil;
import com.comecrd.util.WechatUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/user")
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private WechatUtil wechatUtil;
    
    @Autowired
    private JWTUtil jwtUtil;
    
    // 微信登录
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> request) {
        String code = request.get("code");
        
        // 调用微信API获取openId
        Map<String, String> wxResult = wechatUtil.wxLogin(code);
        
        if (wxResult.containsKey("error")) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", wxResult.get("error"));
            return ResponseEntity.badRequest().body(response);
        }
        
        String openId = wxResult.get("openId");
        
        // 查找或创建用户
        User user = userService.findByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setOpenId(openId);
            user = userService.saveOrUpdate(user);
        }
        
        // 生成JWT令牌
        String token = jwtUtil.generateToken(openId);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("token", token);
        response.put("user", userService.convertToDTO(user));
        
        return ResponseEntity.ok(response);
    }
    
    // 更新用户信息
    @PostMapping("/update")
    public ResponseEntity<Map<String, Object>> updateUser(@RequestHeader("Authorization") String token, @RequestBody UserDTO userDTO) {
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        // 更新用户信息
        if (userDTO.getNickname() != null) user.setNickname(userDTO.getNickname());
        if (userDTO.getAvatarUrl() != null) user.setAvatarUrl(userDTO.getAvatarUrl());
        if (userDTO.getGender() != null) user.setGender(userDTO.getGender());
        // 仅更新User实体中存在的字段
        
        user = userService.saveOrUpdate(user);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("user", userService.convertToDTO(user));
        
        return ResponseEntity.ok(response);
    }
    
    // 获取用户信息
    @GetMapping("/info")
    public ResponseEntity<Map<String, Object>> getUserInfo(@RequestHeader("Authorization") String token) {
        // 从token中获取openId
        String openId = jwtUtil.getOpenIdFromToken(token.replace("Bearer ", ""));
        
        // 查找用户
        User user = userService.findByOpenId(openId);
        if (user == null) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("message", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("user", userService.convertToDTO(user));
        
        return ResponseEntity.ok(response);
    }
}